package com.yundingai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yundingai.domain.dto.UserDTO;
import com.yundingai.domain.entity.AllUser;
import com.yundingai.domain.entity.UserFriend;
import com.yundingai.domain.dto.FriendRequestDTO;
import com.yundingai.domain.entity.UserSocialData;
import com.yundingai.mapper.UserFriendMapper;
import com.yundingai.mapper.AllUserMapper;
import com.yundingai.mapper.UserSocialDataMapper;
import com.yundingai.service.FriendService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
 * @Author HuangZhengmin
 * @desc
 * @Date 2025/7/22 14:29
 * @Version 1.0
 */
@Service
public class FriendServiceImpl implements FriendService {
    @Autowired
    private UserFriendMapper userFriendMapper;
    @Autowired
    private AllUserMapper allUserMapper;
    @Autowired
    private UserSocialDataMapper userSocialDataMapper;

  @Override
  public void sendFriendRequest(Integer fromUserId, Integer toUserId) {
    // 检查是否添加自己为好友
    if (fromUserId.equals(toUserId)) {
      throw new IllegalArgumentException("不能添加自己为好友");
    }

    // 检查是否已存在关系
    List<UserFriend> existingRelations = userFriendMapper.findRelationBetweenUsers(fromUserId, toUserId);
    if (!existingRelations.isEmpty()) {
      // 如果已存在关系，则抛出异常
      throw new IllegalArgumentException(existingRelations.get(0).getStatus() == 1 ?
              "你们已经是好友了" : "好友请求已存在");
    }

    // 创建好友请求
    UserFriend friendRequest = new UserFriend();
    friendRequest.setUserId(toUserId); //userId是审核人
    friendRequest.setFriendId(fromUserId); //friendId是申请人
    friendRequest.setStatus(0); // 0表示待审核
    friendRequest.setCreateTime(new Date());

    // 插入好友请求
    userFriendMapper.insert(friendRequest);
  }

  /**
   *
   * @param requestId  ufID
   * @param userId    用户ID
   * @param accept 是否接受请求
   */
  @Override
  public void respondToFriendRequest(Integer requestId, Integer userId, boolean accept) {
    // 根据请求id查询好友请求 userId是审核人
    UserFriend request = userFriendMapper.selectById(requestId);
    // 如果请求不存在或者审核的用户id不等于传入的用户id，抛出异常
    if (request == null || !request.getUserId().equals(userId)) {
      throw new IllegalArgumentException("无效的好友请求");
    }

    if (accept) {
      // 更新原请求状态为已通过
      request.setStatus(1); // 1表示已通过
      request.setUpdateTime(new Date());
      userFriendMapper.updateById(request);

      // 创建反向关系记录 暂时不需要
//      UserFriend reverseRelation = new UserFriend();
//      reverseRelation.setUserId(userId);
//      reverseRelation.setFriendId(request.getUserId());
//      reverseRelation.setStatus(1); // 1表示已通过
//      reverseRelation.setCreateTime(new Date());
//      userFriendMapper.insert(reverseRelation);
    } else {
      // 更新请求状态为已拒绝
      request.setStatus(2); // 2表示已拒绝
      request.setUpdateTime(new Date());
      userFriendMapper.updateById(request);
    }
  }

  @Override
  public List<FriendRequestDTO> getFriendRequests(Integer userId) {
    // 根据用户ID获取待审核的好友请求(当前用户是审核人)
    List<UserFriend> pendingRequests = userFriendMapper.findPendingRequests(userId);
    if (pendingRequests.isEmpty()) {
      return Collections.emptyList();
    }

    // 获取请求发起者ID列表
    List<Integer> fromUserIds = pendingRequests.stream()
            .map(UserFriend::getFriendId)
            .collect(Collectors.toList());

    // 批量查询用户信息(修复参数传递方式)
    QueryWrapper<AllUser> queryWrapper = new QueryWrapper<>();
    queryWrapper.in("user_id", fromUserIds)
            .eq("status", 1); // 只查询状态正常的用户
    List<AllUser> fromUsers = allUserMapper.selectList(queryWrapper);

    Map<Integer, AllUser> userMap = fromUsers.stream()
            .collect(Collectors.toMap(AllUser::getUserId, Function.identity()));

    // 构建DTO列表
    return pendingRequests.stream().map(request -> {
      FriendRequestDTO dto = new FriendRequestDTO();
      dto.setUfId(request.getUfId());
      dto.setFromUserId(request.getFriendId());
      dto.setToUserId(userId);
      dto.setStatus(request.getStatus());
      dto.setCreateTime(request.getCreateTime());

      AllUser fromUser = userMap.get(request.getFriendId());
      if (fromUser != null) {
        dto.setFromUsername(fromUser.getUsername());
        dto.setFromNickname(fromUser.getNickname());
        dto.setFromAvatarUrl(fromUser.getAvatarUrl());
      }

      return dto;
    }).collect(Collectors.toList());
  }

  @Override
  public List<UserDTO> getMyFriends(Integer userId) {
    // 1. 参数校验
    if (userId == null || userId <= 0) {
      throw new IllegalArgumentException("用户ID无效");
    }

    // 2. 查询好友关系（双向关系，status=1表示已通过的好友）
    List<Integer> friendIds = userFriendMapper.findFriendIdsByUserId(userId);
    if (CollectionUtils.isEmpty(friendIds)) {
      return Collections.emptyList();
    }

    // 3. 批量查询用户基本信息
    List<AllUser> friends = allUserMapper.selectBatchIds(friendIds);
    if (CollectionUtils.isEmpty(friends)) {
      return Collections.emptyList();
    }

    // 4. 批量查询社交数据（优化性能）
    Map<Integer, UserSocialData> socialDataMap = userSocialDataMapper
            .selectList(new QueryWrapper<UserSocialData>().in("user_id", friendIds))
            .stream()
            .collect(Collectors.toMap(UserSocialData::getUserId, data -> data));

    // 5. 组装DTO
    return friends.stream().map(user -> {
      UserDTO dto = new UserDTO();
      // 复制AllUser属性
      BeanUtils.copyProperties(user, dto);

      // 添加社交数据
      UserSocialData socialData = socialDataMap.get(user.getUserId());
      if (socialData != null) {
        dto.setEducationInfo(socialData.getEducationInfo());
        dto.setWorkInfo(socialData.getWorkInfo());
        dto.setLocationInfo(socialData.getLocationInfo());
      }
      return dto;
    }).collect(Collectors.toList());
  }
}

